package com.wondersgroup.retrofittest.login.presenter;
 import com.anupcowkur.reservoir.Reservoir;
 import com.hss.mvp.AbstractPresenter;
 import com.hss.rxjava.ApiCallback;
 import com.hss.rxjava.ApiManager;
 import com.hss.rxjava.bean.Login;
 import com.hss.rxjava.result.ResultObject;
 import com.wondersgroup.retrofittest.constants.ConstantsStr;
 import com.wondersgroup.retrofittest.login.contract.ILoginContract;
 import com.wondersgroup.retrofittest.login.model.LoginModelImpl;
 import com.wondersgroup.retrofittest.mall.MallActivity;

 import java.io.IOException;

 import rx.Observable;


/**
* Created by Administrator on 2017/02/07
*/

public class LoginPresenterImpl  extends AbstractPresenter implements  ILoginContract.Presenter{
    ILoginContract.View mvpView;
    ILoginContract.Model model;

    public LoginPresenterImpl() {
        model = new LoginModelImpl();
    }

    @Override
    public void login(String name, String pwd) {
        mvpView.showLoadingDialog();
            addSubscription((Observable) model.login(name, pwd), new ApiCallback<ResultObject<Login>>(){
                @Override
                public void onSuccess(ResultObject<Login> result) {
//                    mvpView.showToast("登入接口反问成功");
                    if (result.response.userInfo != null){
                        String userId = result.response.userInfo.userId;
                        ApiManager.getInstance().addHeader("token", result.response.userInfo.getToken());
                        ApiManager.getInstance().addHeader("userId", userId);
                        try {
                            Reservoir.put("userId", userId);
                            Reservoir.put(ConstantsStr.LOGIN_INFO_CACHE, result.response.userInfo);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        mvpView.startActy(MallActivity.class);
                        mvpView.finishActivity();
                    }

                }

                @Override
                public void onFailure(String msg) {
                    mvpView.showToast(msg);
                }

                @Override
                public void onFinish() {
                    mvpView.hideLoadingDialog();
                }

                @Override
                public void onDataErr(String msg) {
                    mvpView.showToast(msg);
                }

                @Override
                public void onExitLogin() {
                    mvpView.showToast("重新登入");

                }
            });
    }


    @Override
    public void attachView(ILoginContract.View mvpView) {
        this.mvpView = mvpView;
    }

    @Override
    public void detachView() {
        this.mvpView = null;
        onUnsubscribe();
    }

    @Override
    public void destoryRes() {
        model = null;
        clearSubscription();
    }
}